package com.cloudcc.mobile.view.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.MenuToggleEventR;
import com.cloudcc.cloudframe.ui.viewgroup.loadmore.LoadMoreContainer;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrFrameLayout;
import com.cloudcc.cloudframe.util.ListUtils;
import com.cloudcc.mobile.ExtraConstant;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.BaobiaoListAdapter;
import com.cloudcc.mobile.adapter.BeauShiTuAdapter;
import com.cloudcc.mobile.entity.beau.BeauListEntity;
import com.cloudcc.mobile.entity.beau.BeauListFilterEntity;
import com.cloudcc.mobile.event.BeauEventList;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.presenter.BeauPresenter;
import com.cloudcc.mobile.util.PopuWindowUtils;
import com.cloudcc.mobile.util.ViewUtils;
import com.cloudcc.mobile.view.base.BaseSlidingRightActivity;
import com.cloudcc.mobile.view.web.Newwebview1;
import com.cloudcc.mobile.weight.viewgroup.SoftKeyboardHandledLinearLayout;
import com.cloudcc.mobile.widget.listview.CloudCCListView;
import com.litesuits.android.log.Log;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by lin on 2017/8/31.
 */

public class BaobiaoDetailActivity extends BaseSlidingRightActivity implements CloudCCListView.OnRefreshOrLoadMoreListener, AdapterView.OnItemClickListener, SoftKeyboardHandledLinearLayout.SoftKeyboardVisibilityChangeListener {


    @Bind(R.id.toastHintContent)
    TextView toastHintContent;
    @Bind(R.id.topLayoutBackg)
    RelativeLayout topLayoutBackg;
    @Bind(R.id.imgDeletes)
    ImageView imgDeletes;
    @Bind(R.id.layoutTop)
    FrameLayout layoutTop;

    private boolean mIs = true;
    @Bind(R.id.testsss)
    CloudCCListView mListView;

    @Bind(R.id.layoutHeight)
    LinearLayout layoutHeight;

    @Bind(R.id.container1)
    RelativeLayout rlButtom;


    @Bind(R.id.topLineLayout)
    LinearLayout topLineLayout;

    @Bind(R.id.et_search_content)
    EditText mSearchContent;

    @Bind(R.id.ll_searchparent)
    LinearLayout ll_searchparent;

    @Bind(R.id.no_result_layout_beaulist)
    LinearLayout noResultLayout;

    @Bind(R.id.container)
    SoftKeyboardHandledLinearLayout container;
    @Bind(R.id.tv_hight)
    TextView tv_hight;
    @Bind(R.id.btnLayoutSearch)
    RelativeLayout btnLayoutSearch;
    @Bind(R.id.right_lingdang)
    ImageView right_lingdang;
    @Bind(R.id.back)
    ImageView back;
    public static String mToastStr;
    //上面视图的图片
//	@Bind(R.id.menu_image_bg)
//	ImageView menu_image_bg;
    @Bind(R.id.menu_add_icon)
    ImageView menu_add_icon;
    @Bind(R.id.textViewCoustom)
    TextView textViewCoustom;

    @Bind(R.id.toutextview)
    TextView toutextview;
    @Bind(R.id.sx_iv)
    ImageView sx_iv;
    @Bind(R.id.paixu_iv)
    ImageView paixu_iv;
    @Bind(R.id.create_iv)
    ImageView create_iv;
    private PopupWindow mCreatepop;
    private PopupWindow mSearchView;
    @Bind(R.id.popdingwei)
    TextView popdingwei;
    @Bind(R.id.text_heji_duixiang)
    TextView hejitext;

    //消息数量
    @Bind(R.id.message_num_tz)
    TextView message_num_tz;
    @Bind(R.id.message_num_99)
    TextView message_num_99;

    @Bind(R.id.baobiao_yindao_layout)
    RelativeLayout baobiaoYindao;
    @Bind(R.id.near_by_yindao_ob4)
    ImageView baobiaoYindaoBt;


    private BeauPresenter.FilterCondition mFilterCondition = null;//查新条件bean
    private String mEns = RunTimeManager.getInstance().getlanguage();

    //传递过来的值
    private String mEntityName = "对象列表";
    private String mEntityId;
    private String mNewUrl;
    private String ImageID;

    private List<BeauListFilterEntity.SearchView> listSerch;//报表专用
    private BeauPresenter mBeauPresenter = new BeauPresenter();//网络请求封装
    private boolean isShowShiTuView;//是否显示文件列表
    private BeauListFilterEntity mFilter;
    private String folderId;//选中的文件id
    public boolean isUp = true;
    private int postPage = 1;//请求页码
    private BaobiaoListAdapter mAdapter;
    private List<BeauListEntity> listbeau = new ArrayList<>();
    SharedPreferences yindaoShare;//记录是否第一次登陆，是否需要引导
    private boolean isFirst = true;//是否是第一次登陆
    /**
     * 是否是第一次请求 如果是第一次请求 就 先请求 筛选条件
     */
    private boolean isFristRequest = true;

    private boolean isRequest = false;//是否是下拉刷新

    @Override
    public int getLayoutId() {
        return R.layout.beau_list_frag_type;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
        initPopup();
    }

    private BeauShiTuAdapter adapter;

    private void initPopup() {
        //父级列表显示的adapter
        View contentView = (View) View.inflate(mContext,
                R.layout.beau_search_shitu, null);
        ListView listView = (ListView) contentView.findViewById(R.id.listview2);
        adapter = new BeauShiTuAdapter(mContext);
        listView.setAdapter(adapter);

        DisplayMetrics dm = new DisplayMetrics();
        // 获取屏幕信息
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenWidth = dm.widthPixels;
        int screenHeigh = dm.heightPixels;
//        mSearchView = new PopupWindow(contentView, screenWidth,
//                LinearLayout.LayoutParams.MATCH_PARENT);
        mSearchView = new PopupWindow(contentView, screenWidth,
                screenHeigh - layoutHeight.getHeight() - getStatusBarHeight());
        mSearchView.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.white)));
        mSearchView.setFocusable(false);
        mSearchView.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                isShowShiTuView = false;
            }
        });

        adapter.setmOnSelectItemListener(new BeauShiTuAdapter.OnSelectItemListener() {
            @Override
            public void onSelectItem(int pos, BeauListFilterEntity.SearchView t) {
                mShiTuSelectPos = pos;
                folderId = t.id;
//				requestData();
                isUp = true;
                mListView.requestRefresh();
                textViewCoustom.setText(t.label);
                mIs = true;
                mListView.setVisibility(View.VISIBLE);
                PopuWindowUtils.dissmiss(mSearchView);
                Drawable nav_up = getResources().getDrawable(R.drawable.listviewup);
                nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
                textViewCoustom.setCompoundDrawables(null, null, nav_up, null);
            }
        });
    }

    public void init() {
        EventEngine.register(this);
        initHeader();
        mFilterCondition = new BeauPresenter.FilterCondition();
        mListView.setOnRefreshOrLoadMoreListener(this);
        mListView.setOnItemClickListener(this);
        mAdapter = new BaobiaoListAdapter(mContext);
        mListView.setAdapter(mAdapter);
        if ("en".equals(mEns)) {
            mSearchContent.setHint("Search  " + mEntityName);
        } else {
            mSearchContent.setHint("搜索  " + mEntityName);
        }
        mListView.requestRefresh();
        if ("en".equals(mEns)) {
            textViewCoustom.setText("Recent " + mEntityName);
        } else {
            textViewCoustom.setText("最近" + mEntityName);
        }
        hejitext.setVisibility(View.GONE);

        yindaoShare = getSharedPreferences("NearByYinDao", 0);
        isFirst = yindaoShare.getBoolean("IsFirstBaobiao", true);
        if (isFirst) {
            baobiaoYindao.setVisibility(View.VISIBLE);
        } else {
            baobiaoYindao.setVisibility(View.GONE);
        }

        container.setOnSoftKeyboardVisibilityChangeListener(this);
        rlButtom.setVisibility(View.GONE);//不显示底部栏

        initEdit();

        listSerch = new ArrayList<>();

        //铃铛点击事件
        right_lingdang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventEngine.post(new MenuToggleEventR(false, false));
            }
        });
        //返回点击事件
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        baobiaoYindao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences.Editor editor = yindaoShare.edit();
                editor.putBoolean("IsFirstBaobiao", false);
                editor.commit();
                baobiaoYindao.setVisibility(View.GONE);
            }
        });


    }

    @Override
    protected void onResume() {
        super.onResume();
        mListView.requestRefresh();
    }

    private void initHeader() {


        Intent bundle = getIntent();
        if (bundle != null) {
            mEntityName = bundle.getStringExtra(ExtraConstant.EXTRA_NAME);
            mEntityId = bundle.getStringExtra(ExtraConstant.EXTRA_ID);
            mNewUrl = bundle.getStringExtra(ExtraConstant.EXTRA_URL);
            ImageID = bundle.getStringExtra("imageId");
        }
        ((TextView) findViewById(R.id.header_title)).setText(mEntityName);
        try {
            Class drawable = R.drawable.class;
            Field field = drawable.getField(ImageID + "_1");
            int id = field.getInt(field.getName());
            menu_add_icon.setImageBitmap(null);
            menu_add_icon.setBackgroundResource(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initEdit() {
        mSearchContent.setOnEditorActionListener(new EditText.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    InputMethodManager imm = (InputMethodManager) v
                            .getContext().getSystemService(
                                    Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    clickSearch();
                    return true;
                }
                return false;
            }
        });
    }


    public void clickSearch() {
        InputMethodManager imm = (InputMethodManager) mContext
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mSearchContent.getWindowToken(), 0);
        mListView.requestRefresh();
    }


    @OnClick(R.id.btnLayoutSearch)
    public void clickMore() {
        if (mIs) {
            showShiTuView();
            Drawable nav_up = getResources().getDrawable(R.drawable.listviewdown);
            nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
            textViewCoustom.setCompoundDrawables(null, null, nav_up, null);
            mIs = false;
        } else {
            Drawable nav_up = getResources().getDrawable(R.drawable.listviewup);
            nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
            textViewCoustom.setCompoundDrawables(null, null, nav_up, null);
            PopuWindowUtils.dissmiss(mSearchView);
            mListView.setVisibility(View.VISIBLE);
            mIs = true;
        }

    }

    /**
     * 刷新服务器的菜单列表
     */
    private void requestFilter() {
        mBeauPresenter.getBeanFilter(mEntityId);
    }

    /**
     * 是否有过滤菜单的数据
     *
     * @return
     */
    private boolean hasFilter() {
        return mFilter != null;
    }

    /**
     * 是否有 过滤中的 视图菜单数据
     *
     * @return
     */
    private boolean hasShiTuViewData() {
        return hasFilter() && !ListUtils.isEmpty(mFilter.search_view);
    }

    public int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 显示 一级文件列表 视图标签
     */
    private int mShiTuSelectPos = 0;

    private void showShiTuView() {
        if (isShowShiTuView) {
            return;
        }
        if (!hasShiTuViewData()) {
            requestFilter();
            return;
        }
        // 存在数据
        PopuWindowUtils.dissmiss(mSearchView);

        BeauListFilterEntity.SearchView searchView = new BeauListFilterEntity.SearchView();
        searchView.label = getString(R.string.zuijinbaobiao);
        searchView.id = "recentReport";
        listSerch.clear();
        listSerch.add(searchView);
        listSerch.addAll(mFilter.search_view);
        adapter.clear();
        adapter.addData(listSerch);
        adapter.setSelectItem(mShiTuSelectPos);

        // 测量listview
//        int totalHeightofListView = ViewUtils
//                .getTotalHeightofListView(listView);

        if (Build.VERSION.SDK_INT >= 24) {
            int[] a = new int[2];
            btnLayoutSearch.getLocationInWindow(a);
            mSearchView.showAtLocation(((Activity) mContext).getWindow().getDecorView(), Gravity.NO_GRAVITY, 0, a[1] + btnLayoutSearch.getHeight());
        } else {
            mSearchView.showAsDropDown(btnLayoutSearch);
        }

        mListView.setVisibility(View.GONE);

    }

    /**
     * 获取 beau筛选成功
     *
     * @param event
     */
    public void onEventMainThread(BeauEventList.BeauListFilterEvent event) {
        if (event.isError()) {
            mListView.refreshComplete();
            noResultLayout.setVisibility(View.VISIBLE);
            Toast.makeText(mContext, event.getMessage(), Toast.LENGTH_SHORT).show();
            return;
        }
        this.mFilter = event.getData();
        refreshFilterData();
        // 判断 是否 先 刷新
        //
        if (isFristRequest) {
            isFristRequest = false;
            refresh();
        }
    }

    /**
     * 刷新筛选期的将要使用的数据
     */
    private void refreshFilterData() {
        if (mFilter == null) {
            return;
        }
        if (!ListUtils.isEmpty(mFilter.search_view)) {
            for (int i = 0; i < mFilter.search_view.size(); i++) {
                if (TextUtils
                        .equals(mFilter.search_view.get(i).isdefault, "-1")) {
                    mShiTuSelectPos = i;
                }
            }
        }
    }


    @Override
    public void onRefresh(PtrFrameLayout frame) {
        isRequest = true;
        refresh();
    }

    private void refresh() {
        if (isFristRequest) {// 如果 mfilter空的话 先获取 筛选条件
            requestFilter();
        } else {
            postPage = 1;
            requestData();
        }
    }

    @Override
    public void onLoadMore(LoadMoreContainer frame) {
        isRequest = false;
        postPage++;
        requestData();
    }

    public void requestData() {
        // 取消 视图 popuwindow
        PopuWindowUtils.dissmiss(mSearchView);
        // 获取 检索条件
        if (mFilter == null) {
            return;
        }
        mFilterCondition.pageNum = postPage;
        // 视图
        if (!ListUtils.isEmpty(listSerch)) {
            try {
                BeauListFilterEntity.SearchView searchView;
                searchView = listSerch.get(mShiTuSelectPos);
                mFilterCondition.viewId = searchView.id;
                Log.d("SearchView", searchView.name);

            } catch (Exception e) {
            }

        } else {//文件夹数据为空，未取文件夹数据，默认为最近报表id
            mFilterCondition.viewId = "recentReport";
        }
        // 排序
        mFilterCondition.objectId = mEntityId;
        // 关键字
        mFilterCondition.keyword = mSearchContent.getText().toString();

        mFilterCondition.number = 15;

        mBeauPresenter.getBeanListBaobiao(mFilterCondition);
        mFilterCondition.filterFileds.clear();
    }

//    private boolean isFromRefresh() {
//        return postPage <= 1;
//    }

    private void onRequestFinish(boolean dataIsEmpty, int num) {
        if (isRequest) {// 第一次加载 并且数据出现空的话 就显示 空
            mListView.refreshComplete();
            mListView.isfirst();
            if (dataIsEmpty) {
                noResultLayout.setVisibility(View.VISIBLE);
            }
            if(num < 15){
                mListView.handlerLoadMoreFinish(false, false);// //两个参数：是否是数据为空，是否还有更多(第一次加载数据还有更多)
            }else{
                mListView.handlerLoadMoreFinish(false, true);// //两个参数：是否是数据为空，是否还有更多(第一次加载数据还有更多)
            }
        } else {
            mListView.refreshComplete();
            if(num < 15){
                mListView.handlerLoadMoreFinish(false, false);// //两个参数：是否是数据为空，是否还有更多(第一次加载数据还有更多)
            }else{
                mListView.handlerLoadMoreFinish(false, true);// //两个参数：是否是数据为空，是否还有更多(第一次加载数据还有更多)
            }
        }
    }

    /**
     * 加载到数据
     *
     * @param event
     */
    public void onEventMainThread(BeauEventList.BeauListEvent event) {

        noResultLayout.setVisibility(View.GONE);
        if (event.isError()) {
            if (isRequest) {
                mListView.refreshComplete();
                mListView.handlerLoadMoreFinish(true, false);
                noResultLayout.setVisibility(View.VISIBLE);
            } else {
                mListView.handlerLoadMoreError(1002, event.getMessage());
            }
            return;
        }
        if(ListUtils.isEmpty(event.getData())){//如果得到数据为空
            onRequestFinish(true , 0);//1：是否为空   2：数据个数
            if (mShiTuSelectPos == 0) {
                toutextview.setText("0" + getString(R.string.baobiaolisttitlenew));
            } else {
                toutextview.setText("0" + getString(R.string.baobiaolisttitle));
            }
            return;
        }else{
            onRequestFinish(false , event.getData().size());
        }

        if (isRequest) {//是否是下拉刷新
            listbeau.clear();
            listbeau = event.getData();
            mAdapter.clear();
            mAdapter.addData(event.getData());
        } else {
            mAdapter.addData(event.getData());
        }
        if (mShiTuSelectPos == 0) {
            if(mAdapter.getCount()/15 >= postPage){
                toutextview.setText(15*postPage+ "+" + getString(R.string.baobiaolisttitlenew));
            }else{
                toutextview.setText(mAdapter.getCount() + getString(R.string.baobiaolisttitlenew));
            }
        } else {
            if(mAdapter.getCount()/15 >= postPage){
                toutextview.setText(15*postPage+ "+" + getString(R.string.baobiaolisttitle));
            }else{
                toutextview.setText(mAdapter.getCount() + getString(R.string.baobiaolisttitle));
            }
        }


    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        BeauListEntity t = listbeau.get(position);
        Intent intent = new Intent(this, Newwebview1.class);
        intent.putExtra("url", UrlManager.getRootUrl() + "/weixinlistRunReport.action?reportId=" + t.getId() + "&&returnId=0&&purview=1&&folderId=" + folderId);
        startActivity(intent);
    }

    @Override
    public void onSoftKeyboardShow() {
        rlButtom.setVisibility(View.GONE);
    }

    @Override
    public void onSoftKeyboardHide() {
        InputMethodManager imm = (InputMethodManager) mContext
                .getSystemService(Context.INPUT_METHOD_SERVICE);

        if (getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            rlButtom.setVisibility(View.VISIBLE);
        }
        PopuWindowUtils.dissmiss(mSearchView);
    }
}
